﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Interactivity;

namespace Fluffy.Archive.Behaviors
{
	public class BindableSelectedItemBehavior : Behavior<TreeView>
	{
		public object SelectedItem
		{
			get { return (object)GetValue(SelectedItemProperty); }
			set { SetValue(SelectedItemProperty, value); }
		}

		public static readonly DependencyProperty SelectedItemProperty =
			DependencyProperty.Register("SelectedItem", typeof(object), typeof(BindableSelectedItemBehavior), new UIPropertyMetadata(null));
		
		protected override void OnAttached()
		{
			base.OnAttached();

			AssociatedObject.SelectedItemChanged += OnTreeViewSelectedItemChanged;
		}

		protected override void OnDetaching()
		{
			base.OnDetaching();

			AssociatedObject.SelectedItemChanged -= OnTreeViewSelectedItemChanged;
		}

		private void OnTreeViewSelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
		{
			SelectedItem = e.NewValue;
		}
	}
}
